/**
 * redis数据操作接口
 */

//引入Q模块
var Q = require('q');
//引入redis模块操作redis缓存
var redis = require('redis');
//设置存储客户端实例变量
var client = null;

//连接redis数据库并返回客户端实例函数
var connect = function(redisHost, redisPort, redisOptions) {
	var deferred = Q.defer();
	//建立redis客户端连接
	client = redis.createClient(redisPort, redisHost, redisOptions);
	//返回redis客户端实例
	deferred.resolve(client);
	return deferred.promise;
}

//redis数据库读取对应key的值函数
var get = function(key) {
	var deferred = Q.defer();
	client.get(key, function(err, data) {
		if(err) {
			//读取失败
			deferred.reject(err);
		}
		else {
			//读取成功并返回数据
			deferred.resolve(data);
		}
	});
	return deferred.promise;
}

//redis数据库设置key-value键值函数
var set = function(key, value) {
	var deferred = Q.defer();
	//设置key-value值
	client.set(key, value, function(err, data) {
		if(err) {
			//设置key-value失败
			deferred.reject(err);
		}
		else {
			//判断执行结果是否为OK
			if(data == 'OK') {
				//设置key-value成功
				deferred.resolve(data);
			}
			else {
				//设置key-value失败
				deferred.reject();
			}
		}
	});
	return deferred.promise;
}

//设置对应key值的的生存时间
var expire = function(key, expire) {
	var deferred = Q.defer();
	//尝试设置生存时间
	try{
		client.expire(key, expire);
		//设置成功
		deferred.resolve();
	}
	catch(e) {
		//设置失败
		deferred.reject(e);
	}
	return deferred.promise;
}

//暴露接口
module.exports = {
	client: client,
	connect: connect,
	get: get,
	set: set,
	expire: expire
}